package wsapi

import (
    "fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"live/app/model/px_token"
	"live/app/model/px_user"
	"live/app/service/ws"
	"live/libaray/xout"
)

// 连接
func Conn(r *ghttp.Request) {
	// 验证用户
	token := r.GetHeader("Authorization")
    fmt.Println(token)
	if token == "" {
		xout.StatusCode(r, 500, "token无效")
	}
	tk, err := px_token.Model.Where("token", token).FindOne()
        fmt.Println(tk)
	    fmt.Println(err) 
    if tk == nil {
		xout.StatusCode(r, 503, "token无效")
	}
	if tk == nil || gconv.Int64(tk.Exp) < gtime.Now().Unix() {
		xout.StatusCode(r, 501, "token无效")
	}
	user, _ := px_user.Model.Where("id", tk.UserId).FindOne()
	// user, _ := px_user.Model.Where("id", r.GetInt64("id")).FindOne()
	if user == nil {
		xout.StatusCode(r, 502, "用户不存在")
	}
	conn, _ := r.WebSocket()
	// 登录的用户
	cli := &ws.Client{
		User:    user,
		Request: r,
		Socket:  conn,
	}

	ws.OnOpen(cli)
	defer ws.OnClose(cli)
	// go conn.Heartbeat()
	for {
		// 读消息
		_, msg, err := conn.ReadMessage()
		if err != nil {
			g.Log().Debug("[websocket] ReadMessage err:", err)
			return
		}
		// 处理业务
		go ws.OnMessage(cli, msg)
	}
}

// 加入房间
func JoinRoom(cli *ws.Client, request *ws.Request) {
	out := &ws.JsonData{
		Cmd:    request.Base.Cmd,
		SeqId:  request.Base.SeqId,
		Code:   0,
		Msg:    "SUCCESS",
		Data:   nil,
		Extend: ws.Extend{},
	}
	roomId := request.GetVar("room_id").Int()
	if roomId <= 0 {
		out.Code = 1
		out.Msg = "房间ID错误"
		_ = cli.ReturnJson(out)
		return
	}
	cli.RoomId = roomId
	ws.JoinRoom(cli, roomId)
	_ = cli.Success(out)
}

// 退出房间
func ExitRoom(cli *ws.Client, request *ws.Request) {
	out := &ws.JsonData{
		Cmd:    request.Base.Cmd,
		SeqId:  request.Base.SeqId,
		Code:   0,
		Msg:    "SUCCESS",
		Data:   nil,
		Extend: ws.Extend{},
	}
	roomId := request.GetVar("room_id").Int()
	if roomId <= 0 {
		out.Code = 1
		out.Msg = "房间ID错误"
		_ = cli.ReturnJson(out)
		return
	}
	ws.ExitRoom(cli)
	_ = cli.Success(out)
}
